<template>
  <div class="container">
    <div class="app-container">
      <!-- 按钮 -->
      <el-button type="primary" @click="showDialog= true">添加角色</el-button>
      <!-- 表格 -->
      <el-table :data="list">
        <el-table-column width="300" label="角色" align="center" prop="name">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editObj.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column width="300" label="启用" align="center" prop="state">
          <template #default="{row}">
            <el-switch
              v-if="row.isEdit"
              v-model="row.editObj.state"
              :active-value="1"
              :inactive-value="0"
            />
            <span v-else> {{ row.state === 1 ? '已启用' : '未启用' }}</span>
          </template>
        </el-table-column>
        <el-table-column width="700" label="描述" align="center" prop="description">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editObj.description" size="mini" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{row}">
            <template v-if="row.isEdit">
              <el-button type="primary" size="mini" @click="handleUpdate(row)">确认</el-button>
              <el-button size="mini" @click="cancelEdit(row)">取消</el-button>
            </template>
            <template v-else>
              <el-button size="mini" type="text" @click="showPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="row.isEdit = true">编辑</el-button>
              <el-popconfirm
                title="确定要删除删除吗？"
                @confirm="delRole(row.id)"
              >
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-row type="flex" justify="end" style="margin:20px 0">
        <el-col :span="7">
          <el-pagination
            :current-page="params.page"
            :page-sizes="[2, 4, 6, 8]"
            :page-size="params.pagesize"
            layout=" sizes,prev, pager, next"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-col>
      </el-row>
    </div>
    <!-- 角色弹出框 -->
    <el-dialog
      title="新增角色"
      :visible.sync="showDialog"
      width="30%"
      @close="close"
    >
      <!-- 表单 -->
      <el-form ref="formRef" label-width="100px" :model="form" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="启用" prop="state">
          <el-tooltip :content="'开关状态: ' + (form.state === 1 ? '启用' : '未启用')" placement="top">
            <el-switch
              v-model="form.state"
              :active-value="1"
              :inactive-value="0"
            />
          </el-tooltip>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入角色描述" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addRole">确 定</el-button>
        <el-button @click="close">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限的弹出框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="perDialog"
      width="30%"
      @close="perDialog = false"
    >
      <el-tree
        ref="treeRef"
        default-expand-all
        :data="permissionList"
        :props="{label:'name'}"
        show-checkbox
        :check-strictly="true"
        :default-checked-keys="permIds"
        node-key="id"
      />
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateRoleDetail">确 定</el-button>
        <el-button @click="perDialog = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { reqGetRoleList, reqAddRole, reqUpdateRole, reqDelRole, reqGetRoleDetail, reqUpdateRoleDetail } from '@/api/role'
import { reqGetgetPermissionList } from '../../api/permission'
import { translatetoTreeDate } from '../../utils'
export default {
  name: 'Role',
  data() {
    return {
      id: null, // 点击权限点的角色id
      permIds: [], // 角色关联的权限集合
      perDialog: false, // 分配权限的弹出框
      permissionList: [], // 权限列表
      showDialog: false,
      params: { page: 1, pagesize: 2 },
      list: [], // 角色列表
      total: 0, //   总数
      form: {
        name: '',
        state: 0,
        description: ''
      },
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'change' }],
        description: [{ required: true, message: '请输入角色名称', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 封装获取所有的列表
    async  getRoleList() {
      const { data } = await reqGetRoleList(this.params)
      data.rows.forEach(item => {
        item.isEdit = false
        item.editObj = {
          name: item.name,
          state: item.state,
          description: item.description
        }
      }) // 添加布尔值
      this.list = data.rows
      // console.log(data)
      this.total = data.total
    },
    // 每页多少条 每页条数发生变化
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.params.pagesize = val
      this.getRoleList()
    },
    // 当前页 页码发生变化
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.params.page = val
      this.getRoleList()
    },
    // 关闭对话框
    close() {
      this.showDialog = false
      this.$refs.formRef.resetFields()
    },
    // 表单预校验，并发起请求
    addRole() {
      // 预校验
      this.$refs.formRef.validate(async too => {
        if (too) {
          // console.log(this.form)
          // 发起请求
          await reqAddRole(this.form)
          // 重置表单
          this.close()
          // 渲染页面
          this.params.page = 1
          this.getRoleList()
        }
      })
    },
    // 点击取消按钮，重置输入框的值
    cancelEdit(row) {
      row.isEdit = false
      row.editObj = {
        name: row.name,
        state: row.state,
        description: row.description
      }
    },
    // 点击确认更新信息
    async handleUpdate(row) {
      if (!row.editObj.name) return this.$message.warning('请输入角色名称')
      if (!row.editObj.description) return this.$message.warning('请输入角色描述')
      await reqUpdateRole({ ...row.editObj, id: row.id })
      // 关闭弹框
      // row.isEdit = false
      // row.name = row.editObj.name
      // row.state = row.editObj.state
      // row.description = row.editObj.description
      // 以上错误警告，因为携带了row发送了请求，觉得再去复制row可能会有问题
      // 通过Object.assion，方法进行修改，赋值，将这些数据赋值修改给row
      Object.assign(row, {
        isEdit: false,
        name: row.editObj.name,
        state: row.editObj.state,
        description: row.editObj.description
      })
    },
    // 删除
    async  delRole(id) {
      console.log(11)
      await reqDelRole(id)
      // 判断：当该页的删除后，没有数据了，需要往前进一页
      if (this.list.length === 1 && this.params.page > 1) {
        this.params.page--
      }
      // 重新渲染
      this.getRoleList()
    },
    // 点击分配权限
    async showPermission(id) {
      this.permIds = [] // 处理数据与页面不同步
      this.id = id // 保存id
      const res = await reqGetgetPermissionList()
      // console.log(res)
      this.permissionList = translatetoTreeDate(res.data, 0)
      // 获取角色权限的详情
      const { data } = await reqGetRoleDetail(id)
      // console.log(data)
      this.permIds = data.permIds
      this.perDialog = true
    },
    // 修改角色权限
    async updateRoleDetail() {
      // 通过 this.$refs.treeRef.getCheckedKeys() 获取选中的权限
      // console.log(this.$refs.treeRef.getCheckedKeys())
      // 分配权限，调用分配权限请求的接口
      await reqUpdateRoleDetail(this.id, this.$refs.treeRef.getCheckedKeys())
      // console.log(res)
      this.perDialog = false
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__footer {
  text-align: center;
}
</style>
